
var meme = {}

meme.div_prefix = '';
meme.textarea_prefix = '';
meme.waiting_response = true;
meme.newtempid = 0;
meme.error_if_empty = function(obj) {
    if (!obj.length) {
        console.error('empty object %s:', obj);
        console.dir(obj);
        alert('Error in script');
    }
}
meme.init = function(conf) {
    meme.conf = conf;
    meme.div_prefix = conf.div_prefix;
    meme.textarea_prefix = conf.textarea_prefix;
    meme.waiting_response = false;
    $('.node_content').keypress(function(event) {
        return meme.on_content_keypress(event, this);
    });
    $('#status_message').text('Status: OK');   
    return true;
};

meme.on_content_keypress = function(event, content) {
    //var ctrlEnter = (document.getElementById('submit_key').value == 'ctrl-enter');
    if (event.keyCode == 13 /* enter */ && !event.altKey && !event.shiftKey) {
        //&& event.ctrlKey == ctrlEnter) {
        return meme.create_node(content, 'normal');
    } else if (event.keyCode == 45 /* Insert key */ && !event.altKey && !event.shiftKey) {
        return meme.create_node(content, 'sub');
    } else {
        return true;
    }
};

meme.done_create_node = function(result) {
    console.debug('calling done create node with %s:', result);
    console.dir(result);
    if (result.errors.length > 0) {
        var message = $('#status_message');
        meme.error_if_empty(message);
        message.addClass('error_block');
        message.html('<p class="error_message">Status: Error</p>');
        $.each(result.errors, function(i, errornode) {
            error = '<p class="error_message">' + errornode + '</p>';
            message.append(error);
        });
        var node = $('#' + meme.div_prefix + meme.newtempid);
        meme.error_if_empty(node);       
        node
            .children('.full_position')
                .text('Error. See message above')
                .addClass('error_message error_block')
                .end()
            .children('.spinner')
                .removeClass('spinner_processing')
                .end();
        return false;
    }
    var newid = result.tmpnode.newid;
    var newfullpos = result.tmpnode.newfullpos;
    var oldid = result.tmpnode.tempid;
    var node = $('#' + meme.div_prefix + oldid);
    meme.error_if_empty(node);
    node.attr('id', meme.div_prefix + newid);

    node
        .children('.node_content')
            .attr('id', meme.textarea_prefix + newid)
            .attr('name', meme.textarea_prefix + newid)
            .end()
        .children('.full_position')
            .text(newfullpos)
            .end()
        .children('.spinner')
            .removeClass('spinner_processing')
            .end();

    
    $.each(result.nodes, function(i, memenode) {
        var updatenode = $('#' + meme.div_prefix + memenode.id);
        meme.error_if_empty(updatenode);       
        updatenode
            .children('.full_position')
            .text(memenode.fullpos);
    });
    $('#status_message').text('Status: OK');
    return true;
};

meme.create_node = function(content, nodetype) {
    if (meme.waiting_response)
        return false;

    var textarea = $(content);
    meme.error_if_empty(textarea);
    var node = textarea.parent();
    meme.error_if_empty(node);   
    var clonednode = node.clone(true);
    meme.error_if_empty(clonednode);    
    meme.newtempid = 'tempid';
    clonednode.attr('id', meme.div_prefix + meme.newtempid);
    clonednode.hide();
    $(clonednode)
        .children('.node_content')
            .attr('id', meme.textarea_prefix + meme.newtempid)
            .attr('name', meme.textarea_prefix + meme.newtempid)
            .text('')
            .end()
        .children('.full_position')
            .text('Wait...')
            .end()
        .children('.spinner')
            .addClass('spinner_processing')
            .end();
        
    var subclonednode = $(clonednode).children('.subnode');
    meme.error_if_empty(subclonednode);    
    subclonednode.empty();
    var subnode = $(node).children('.subnode');
    meme.error_if_empty(subnode);   
    if (nodetype == 'sub') {
        $(subnode).append(clonednode); // insert in the subnode container of node
    } else {
        $(node).after(clonednode); // insert in the same level
    }
    $(clonednode).fadeIn('normal');
    $(clonednode).children('.node_content').focus();

    // build the query parameter string
    var params = {};
    if (nodetype == 'sub') {
        params['c'] = 'cs';
    } else {
        params['c'] = 'ci';
    }
    params['id'] = escape(textarea.attr('id'));
    params['tempid'] = meme.newtempid;

    $('#status_message').text('Status: Processing...');

    $.ajax({
        url: meme.conf.ajax_url,
        type: meme.conf.ajax_method,
        data: params,
        dataType: meme.conf.ajax_response,
        timeout: meme.conf.ajax_timeout,
        error: function() {
            alert('Error loading document');
        },
        beforeSend: function(req) {
            meme.waiting_response = true;
        },
        success: function(content) {
            ok = meme.done_create_node(content);
            if (ok)
                meme.waiting_response = false;
        }
    });
    return false;
};

